<?php

use think\Request;
use think\Db;
use app\admin\model\User;
use Overtrue\Pinyin\Pinyin;
/**
 * Undocumented function
 *获取当前域名
 * @return void
 */
function  yuming($data,$zd=''){
    $request = Request::instance();
    $domain = $request->domain();
    $is_array=is_array($data);
    if($is_array=='true'){
        $count=count($data);
        if($count>=1&&$zd==''){
            foreach ($data as $productk=>&$productv){
                // $productv=$domain.$productv;
                if($productv){
                    if(strpos($productv,'http') !== false){
                        $productv=$productv;

                    }else{
                        $productv=$domain.$productv;
                    }
                }
            }
        }elseif($count>=1){
            foreach ($data as $productk=>&$productv){
                if($productv){
                    if(strpos($productv[$zd],'http') !== false){
                        $productv[$zd]=$productv[$zd];
                    }else{
                        $productv[$zd]=$domain.$productv[$zd];
                    }
                }
            }
        }else{
            $data=[];
        }
    }else{
        if($data){
            if($data){
                if(strpos($data,'http') !== false){
                    $data=$data;
                }else{
                    $data=$domain.$data;
                }
            }
        }
    }
    return $data;
}
/**
 * CURL实现GET或POST请求
 * @param $url          请求地址
 * @param $mode         请求方式（GET/POST）
 * @param $data         请求参数，执行POST请求时需要
 * @return object       返回对象数据包
 */
function sCurl($url, $data = array(), $mode = 'GET'){
    // 初始化
    $curl = curl_init();
    // 访问的URL
    curl_setopt($curl, CURLOPT_URL, $url);
    // 只获取页面内容，但不输出
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    // 验证是否是https请求
    if(substr($url, 0, 5) == 'https'){
        // https请求，不验证证书
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // https请求，不验证HOST
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    if($mode == 'POST'){
        // 设置请求方式为POST请求
        curl_setopt($curl, CURLOPT_POST, true);
        // POST请求数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    // 执行CURL请求
    $result = curl_exec($curl);
    // 关闭curl，释放资源
    curl_close($curl);
    return $result;
}
/**
 * 将xml转为array
 * @param  string $xml xml字符串
 * @return array       转换得到的数组
 */
//xml转换成数组
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring), true);
    return $val;
}
/**随机生成订单号
 * Undocumented function
 *
 * @return void
 */
function StrOrderOne(){
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);
    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}


/**
 * 获取客户端IP地址
 */
function real_ip()
{
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}



/**
 *
 *替换富文本中的src
 *
 *
 *
 * */
function replace_image($data){

    $preg = '#<img(.+?)src\s*=\s*[\"|\']([^"|^\']+?)[\"|\']([^>]*?)>#';

    return $data = preg_replace_callback($preg,function ($matches){

        $replace = yuming($matches[2]);//要替换的src


        return "<img{$matches[1]}src=\"$replace\"{$matches[3]} style=\"vertical-align: middle;\">";

    }, $data);
}

//function access_token(){
//    $data=Db::name('access_token')->where(['id'=>1])->find();
//    return $data;
//}
//function admin_pay($admin_id){
//    $data=Db::name('admin')->where(['id'=>$admin_id])->field('appid,mch_id')->find();
//    return $data;
//}



function getDistance($lat1,$lng1,$lat2,$lng2)
{
    //将角度转为狐度
    $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6371;
    return round($s,1);
}


/**
 * [getMonthDays返回指定日期所在月份的第一天和最后一天]
 * @param  [type] $date [日期]
 * @return [type]       [array]
 */
function getMonthDays($date){

    $date=explode('-',$date);

    $month = $date[1]; // 指定月份
    $year = $date[0]; // 当前年份
    $fi=strtotime($year . '-' . $month . '-01 '.'00:00:00');
    $la=strtotime($year . '-' . $month . '-01 '.'23:59:59');
    $firstDay = date('Y-m-01', $fi); // 获取指定月的第一天
    $lastDay = date('Y-m-t', $la); // 获取指定月的最后一天
    $days = date('t', mktime(0, 0, 0, $month, 1, $year));
    return array($firstDay,$lastDay,$fi,$la,$days);
}
/**
 *
 * 匹配省市区
 *
 * */
function city($address){

    preg_match('/(.*?(省|自治区|北京市|天津市))/', $address, $matches);
    if (count($matches) > 1) { $province = $matches[count($matches) - 2];
        $address = str_replace($province, '', $address);

    }
    preg_match('/(.*?(市|自治州|地区|区划|县))/', $address, $matches);
    if (count($matches) > 1)
    {
        $city = $matches[count($matches) - 2]; $address = str_replace($city, '', $address);


    }

    preg_match('/(.*?(区|县|镇|乡|街道))/', $address, $matches);
    if (count($matches) > 1)
    {
        $area = $matches[count($matches) - 2]; $address = str_replace($area, '', $address);

    }

    return [ 'province' => isset($province) ? $province : '', 'city' => isset($city) ? $city : '', 'area' => isset($area) ? $area : '', ];
}

/**
 *
 * 地址首字母转换
 *
 * */
function  address_pinyin ($contractarea_name,$type = null,$num){
    $pinyin = new Pinyin(); // 创建Pinyin实例
    $result = $pinyin->convert($contractarea_name); // 转换
    $name='';
    foreach ($result as &$value){
        $name=$name.substr($value, 0, 1);
    }
    $contracts='';
    if(strlen($num)==1){
        $contracts='000'.($num+1);
    }
    if(strlen($num)==2){
        $contracts='00'.($num+1);
    }
    if(strlen($num)==3){
        $contracts='0'.($num+1);
    }
    if(strlen($num)==4){
        $contracts=($num+1);
    }
    if($type=='HT'){
        $name=strtoupper($name).date('Ymd').$contracts;
    }
    if($type=='KH'){
        $name=strtoupper($name).$contracts;
    }
    if(!$type){
        $name=strtoupper($name);
    }
    return $name;
}


function json_array($json)
{
    return json_decode(json_encode($json),1);
}




function value($value, ...$args)
{
    return $value instanceof Closure ? $value(...$args) : $value;
}
function retry($times, callable $callback, $sleepMilliseconds = 0, $when = null)
{
    $attempts = 0;

    beginning:
    $attempts++;
    $times--;

    try {
        return $callback($attempts);
    } catch (Exception $e) {
        if ($times < 1 || ($when && ! $when($e))) {
            throw $e;
        }

        if ($sleepMilliseconds) {
            usleep(value($sleepMilliseconds, $attempts) * 1000);
        }

        goto beginning;

    }
}

